package com.ziroom.crm.rock.spring.config;

import com.ziroom.crm.mq.core.config.MqConfig;
import com.ziroom.crm.mq.core.logging.Log;
import com.ziroom.crm.mq.core.logging.LogFactory;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.nio.charset.Charset;
import java.util.Objects;
import java.util.function.Consumer;

/**
 * 配置
 *
 * @author WeiShaoying
 * @version 1.0
 * @date Created in 2020年09月07日 19:47
 * @since 1.0
 */
@Data
@ConfigurationProperties(prefix = "crm.mq")
public class MqSpringConfig implements InitializingBean {

    private static final Log log = LogFactory.getLog(MqSpringConfig.class);

    /**
     * 字符集
     */
    private String charset;

    /**
     * 持久type
     */
    private String persistenceType;

    /**
     * 持久化文件路径
     */
    private String persistenceFilePath;

    /**
     * 是否开启内部定时
     */
    private String innerJobEnable;

    /**
     * 是否开启统计
     */
    private String statisticEnable;

    /**
     * 重试相关配置
     */
    private MqRetryConfig retry;

    /**
     * spi 相关config
     */
    private MqSpiConfig spi;

    /**
     * 重新发送的配置
     */
    private MqResendConfig resend;

    /**
     * 重新消费的配置
     */
    private MqReconsumeConfig reconsume;


    @Override
    public void afterPropertiesSet() throws Exception {
        if (StringUtils.isNoneBlank(this.charset)) {
            checkCharset();
            MqConfig.setConfig(MqConfig.charset(), this.charset);
        }

        if (StringUtils.isNoneBlank(this.persistenceType)) {
            MqConfig.setConfig(MqConfig.PERSISTENCE_TYPE, this.persistenceType);
        }
        if (StringUtils.isNoneBlank(this.persistenceFilePath)) {
            MqConfig.setConfig(MqConfig.PERSISTENCE_FILE_PATH, this.persistenceFilePath);
        }

        if (Objects.nonNull(this.innerJobEnable)) {
            boolean innerJobEnable = Boolean.parseBoolean(this.innerJobEnable);
            MqConfig.setConfig(MqConfig.INNER_JOB_ENABLE, Boolean.toString(innerJobEnable));
        }

        if (Objects.nonNull(this.statisticEnable)) {
            boolean statisticEnable = Boolean.parseBoolean(this.statisticEnable);
            MqConfig.setConfig(MqConfig.STATISTIC_ENABLE, Boolean.toString(statisticEnable));
        }

        intiConfig(spi, (a) -> spi.initMqConfigSpi());
        intiConfig(retry, (a) -> retry.initMqConfigRetry());
        intiConfig(resend, (a) -> resend.initMqConfigResend());
        intiConfig(reconsume, (a) -> reconsume.initMqConfigReconsume());
    }

    /**
     * 判断charset正确性
     */
    private void checkCharset() {
        Charset.forName(this.charset);
    }

    private <T> void intiConfig(T config, Consumer<T> consumer) {
        if (Objects.nonNull(config)) {
            consumer.accept(config);
        }
    }

}
